<?php

require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Visitor.php';

class Pipes_ModelList_Grid_ActionBuilder
	implements PipesImpl_Visitor
{
	private $_document = null;
	private $_config = null;
	
	public function __construct(PipesImpl_Config $config, Pipes_Xml_Document $document) {
		$this->_document = $document;
		$this->_config = $config;
	}
	
	public function visit(PipesImpl_Visitable $visitable) {
		$rows = $visitable->getElementsByTagName('tr');
		
		foreach ($rows as $row) {
			if ($row->firstChild->nodeName == 'th') {
				// skip all header rows
				continue;
			}
			$action = $this->_document->createElement('td');
			$row->appendChild($action);

			// divine what type we're working with
			$idAttribute = $row->getAttribute('id');
			preg_match("/row_([a-z]+)_[0-9]*/i", $idAttribute, $matches);
			$elementType = ucfirst($matches[1]);
			
			$edit = $this->_document->createElement('a');
			$href = $this->_document->createAttribute('href');
			$href->nodeValue = $this->_config->base_uri . "{$elementType}/edit/";
			$href->nodeValue .= $row->firstChild->nodeValue;
			$edit->appendChild($href);
			$edit->nodeValue = 'edit';

			$delete = $this->_document->createElement('a');
			$deleteHref = $this->_document->createAttribute('href');
			$deleteHref->nodeValue = $this->_config->base_uri . "{$elementType}/remove/{$row->firstChild->nodeValue}";
			$delete->appendChild($deleteHref);
			$delete->nodeValue = 'delete';
			
			$action->appendChild($edit);
			$action->appendChild($delete);
		}
	}
}
